package com.ryze.common.dubbo.project;

import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.*;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.cluster.LoadBalance;
import org.apache.dubbo.rpc.cluster.support.MergeableClusterInvoker;

import java.util.ArrayList;
import java.util.List;

public class ProjectMergeableClusterInvoker<T> extends MergeableClusterInvoker<T> {
    public ProjectMergeableClusterInvoker(Directory directory) {
        super(directory);
    }


    @Override
    protected Result doInvoke(Invocation invocation, List<Invoker<T>> invokers, LoadBalance loadbalance) throws RpcException {
        List<Invoker<T>> availableInvokers = new ArrayList<>();
        if(ProjectEnvUtils.isProjectEnv()) {
            String projectGroup = RpcContext.getContext().getAttachment("projectGroup");
            if (StringUtils.isBlank(projectGroup)) {
                projectGroup = ProjectEnvUtils.getGroup();
            }
            if (!StringUtils.isBlank(projectGroup)) {
                for (Invoker<T> invoker : invokers) {
                    if (projectGroup.equals(invoker.getUrl().getParameter(CommonConstants.GROUP_KEY))) {
                        availableInvokers.add(invoker);
                    }
                }
            }
            if (CollectionUtils.isEmpty(availableInvokers)) {
                for (Invoker<T> invoker : invokers) {
                    if (ProjectEnvUtils.STABLE_ENV.equals(invoker.getUrl().getParameter(CommonConstants.GROUP_KEY))) {
                        availableInvokers.add(invoker);
                    }
                }
            }
        }else{
            availableInvokers = invokers;
        }
        return super.doInvoke(invocation, availableInvokers, loadbalance);
    }
}